import axios from "axios";
import LogUtil from "./LogUtil";
import Toast from "../view/Toast";
import { locationTo } from "./LocationUtil";
import * as locations from "../const/locations";

// 域名
const PATH = 'http://prop.financesd.cn'

/**
 * 状态检测
 * @param response
 */
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300 && response.data) {
    return response;
  }
  let err = new Error(response.status);
  err.response = response.status;
  err.message = "服务器出错了!";
  throw err;
}

/**
 * 统一错误处理
 * @param response
 */
// 根据服务器接口数据格式处理
function parseErrorMessage(response) {
  // LogUtil.log("server data：", response);
  let error_code, msg, data;
  try {
    error_code = response.data.error_code;
    msg = response.data.msg;
    data = response.data;
  } catch (e) {
    let err = new Error("数据格式错误！");
    err.name = "typeError";
    throw err;
  }

  if (error_code === 0) {
    return data;
  } else if (error_code >= 100 && error_code <= 105) {
    locationTo(locations.LOGIN)
    return data;
  } else {
    return data;
  }



  // return response.data;

  // let err = new Error();
  // err.message = msg;
  // throw err;
}

/**
 * post参数对象转FormData
 * @param params
 * @returns {*}
 */
function paramsToFormData(params) {
  if (!params) {
    return {};
  }
  if (params instanceof FormData) {
    return params;
  }
  let fd = new FormData();
  for (let p in params) {
    fd.append(p, params[p]);
  }
  return fd;
}

/**
 * post请求
 * @param url
 * @param data
 * @returns {Promise<void>}
 */
export async function post(url, data) {
  data = paramsToFormData(data);
  return new Promise(function (resolve, reject) {
    return axios
      .post(PATH + url, data, { headers: { "X-Requested-With": "XMLHttpRequest" } })
      .then(checkStatus)
      .then(parseErrorMessage)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        if (err.name === "customErr") {
          Toast.info(err.message, 3500);
          reject(err);
        } else {
          Toast.info(err.message, 3500);
        }
      });
  });
}

/**
 * get请求
 * @param url
 * @returns {Promise<void>}
 */
export async function get(url, data) {
  url = paramsToString(url, data)
  return new Promise(function (resolve, reject) {
    return axios
      .get(PATH + url)
      .then(checkStatus)
      .then(parseErrorMessage)
      .then(function (result) {
        resolve(result);
      })
      .catch(function (err) {
        reject(err);
        LogUtil.err(err);
      });
  });
}

/**
 * get参数对象转字符串
 * @param params
 * @returns {*}
 */
function paramsToString(url, data) {
  url = url + '?'
  for (let item in data) {
    url = url + item + '=' + data[item] + '&'
  }
  return url
}